package uk.ac.cam.tcs40.sidnet.formal;

import uk.ac.cam.tcs40.sidnet.Hall;
import uk.ac.cam.tcs40.sidnet.R;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FormalListFragment extends Fragment {

	private ArrayAdapter<Formal> m_FormalListAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		super.onCreateView(inflater, container, savedInstanceState);

		// Inflate the layout for this fragment
		final View view = inflater.inflate(R.layout.activity_formal_list, container, false);

		final ListView formalListView = (ListView) view.findViewById(R.id.formal_list);

		m_FormalListAdapter = new ArrayAdapter<Formal>(getActivity(), android.R.layout.simple_list_item_1, Hall.getInstance().getFormals());
		formalListView.setAdapter(m_FormalListAdapter);

		formalListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				Formal formal = (Formal)parent.getItemAtPosition(position);

				Intent intent = new Intent(getActivity(), FormalActivity.class);
				intent.putExtra("id", formal.getID());
				getActivity().startActivity(intent);
			}
		});

		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		new DownloadFormalListTask().execute();
	}

	private class DownloadFormalListTask extends AsyncTask<Void, Void, Void> {
		protected void onPreExecute() {
		}

		protected Void doInBackground(Void... v) {
			if (!Hall.getInstance().haveDownloadedFormals()) {
				int id = Hall.getInstance().downloadFormalList();
				publishProgress();
				while (Hall.getInstance().findFormals(++id))
					publishProgress();
			}
			return null;
		}

		protected void onProgressUpdate(Void... progress) {
			m_FormalListAdapter.notifyDataSetChanged();
		}

		protected void onPostExecute(Void result) {
			m_FormalListAdapter.notifyDataSetChanged();
		}
	}
}
